// pages/chat/chat.js
import { personInfo, bpSaveMsg } from '../../api/index'
import { showToast } from '../../utils/toast'
import { qaChat } from '../../utils/chat'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    autoSize: {
      maxHeight: 160,
      minHeight: 36
    },
    textarea: '',
    messageList: [],
    queryLoading: false,
    remainingScore: 0  //剩余积分
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getPersonInfo(2)
  },
  // 获取个人会员信息
  async getPersonInfo(queryType) {
    let result = await personInfo({
      queryType: queryType === 2 ? 2 : 1
    })
    this.setData({
      remainingScore: result.remainingScore
    })
  },
  // 发送数据
  async sendData() {
    let { textarea, messageList } = this.data
    if (!textarea.trim()) {
      showToast('请输入内容')
      return
    }
    let messageObj = {
      direction: 'O',
      contextMsg: textarea.trim(),
      chatType: 'chat',
      model: 'zpGLM',
      terminalType: 'h5'
    }
    messageList.push(messageObj)
    this.setData({
      textarea: '',
      messageList,
      queryLoading: true
    })
    this.scrollHandle()
    try {
      await bpSaveMsg(messageObj)
      const result = await qaChat(messageObj.contextMsg)
      const { body, status } = result
      // BOT empty message
      const emptyMessageObj = {
        ...messageObj,
        contextMsg: '',
        direction: 'I',
        responseStatus: 'waitLoading',
        like: '',
        talent: '',
      }
      messageList.push(emptyMessageObj)
      this.setData({
        messageList
      })
      this.scrollHandle()
      if (body) {
        const reader = body.getReader()
        await this.readStream(reader)
      }
    } catch (error) {
      console.info('error')
      console.info(error)
      const messageObj = messageList[messageList.length - 1]
      if (messageObj.responseStatus === 'waitLoading') {
        if (messageObj.contextMsg) {
          messageObj.responseStatus = ''
          await bpSaveMsg(messageObj)
          this.getPersonInfo()
        } else {
          messageList.pop()
        }
      }
      this.setData({
        queryLoading: false,
        messageList
      })
    }
  },
  // 读取sse流
  async readStream(reader) {
    let { messageList } = this.data
    let partialLine = ''

    const decoder = new TextDecoder('utf-8')

    // eslint-disable-next-line no-constant-condition
    while (true) {
      // eslint-disable-next-line no-await-in-loop
      const { value, done } = await reader.read()
      if (done) break

      const decodedText = decoder.decode(value, { stream: true })

      // if (status !== 200) {
      // TODO: 错误处理
      // }

      const chunk = partialLine + decodedText
      const newLines = chunk.split(/\r?\n/)

      partialLine = newLines.pop() ?? ''

      for (const line of newLines) {
        console.log(line)
        if (line.length === 0) continue // 忽略空消息
        if (line.startsWith(':')) continue // 忽略SSE的注释
        if (line.startsWith('retry:')) continue // 忽略重试
        // if (line === "data:[DONE]") return // 结束

        if (line === 'id:[DONE]') {
          // TODO 回调函数形式
          const messageObj = messageList[messageList.length - 1]
          messageObj.responseStatus = ''
          // 保存bot消息
          await bpSaveMsg(messageObj)
          this.setData({
            queryLoading: false,
            messageList
          })
          this.getPersonInfo()
          return
        }
        let line_json = JSON.parse(line.substring(5)) // start with "data: "
        // console.log(line_json)
        const content = line_json.content
        this.appendLastMessageContent(content)
      }
    }
  },
  // 追加到最新一条消息
  appendLastMessageContent(content) {
    let messageList = this.data.messageList
    let index = messageList.length - 1
    this.setData({
      [`messageList[${index}].contextMsg`]: messageList[index].contextMsg + content
    })
    this.scrollHandle()
  },
  // 滚动到底部
  scrollHandle() {
    console.info('滚动')
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  // 消息记录
  goRecord() {
    wx.navigateTo({
      url: '../record/record'
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

})